import React, { useState, useRef, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  FlatList,
  KeyboardAvoidingView,
  Platform,
  Dimensions,
  ActivityIndicator
} from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';

const MAX_WIDTH = 480;
const screenWidth = Dimensions.get('window').width;
const contentWidth = screenWidth > MAX_WIDTH ? MAX_WIDTH : screenWidth;

// 预设的客服自动回复
const autoReplies = [
  '您好，很高兴为您服务！请问有什么可以帮助您的？',
  '感谢您的咨询，我们会尽快处理您的问题。',
  '您可以提供更多详细信息，以便我们更好地帮助您解决问题。',
  '请稍等片刻，我正在查询相关信息。',
  '如果您有任何其他问题，随时可以咨询我们。',
];

// 问题对应的回答映射表
const questionAnswers = {
  '如何找回账号密码？': '您可以通过绑定的手机号或邮箱进行密码重置，或联系客服提供账号信息和身份证明，我们会协助您找回账号。',
  '充值没到账怎么办？': '请提供您的充值订单号和账号信息，我们会为您核实充值状态并处理。一般情况下，充值会在15分钟内到账。',
  '如何申请退款？': '根据平台规定，您可以在购买后24小时内申请退款，请提供订单号和退款原因，我们会尽快处理您的退款申请。',
  '游戏账号被盗怎么办？': '请立即修改密码并联系客服，提供账号信息和相关证明，我们会协助您处理账号安全问题并追回损失。',
  '如何举报违规行为？': '您可以通过游戏内举报功能或联系客服提供违规证据，我们会认真核实并严肃处理违规行为，维护游戏环境。',
  '游戏内交易安全保障？': '平台提供担保交易服务，交易双方确认后才会完成交易。如遇欺诈行为，请保留证据并联系客服处理。',
};

// 随机获取一条自动回复
const getRandomReply = () => {
  const index = Math.floor(Math.random() * autoReplies.length);
  return autoReplies[index];
};

// 根据问题获取对应回答
const getAnswerForQuestion = (question) => {
  return questionAnswers[question] || getRandomReply();
};

const ChatInterface = ({ onClose, initialQuestion = null }) => {
  const [messages, setMessages] = useState([]);
  const [inputText, setInputText] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const flatListRef = useRef(null);

  // 初始化客服欢迎消息
  useEffect(() => {
    const welcomeMessage = {
      id: Date.now(),
      text: '您好，我是客服小助手，很高兴为您服务！有什么可以帮助您的吗？',
      isUser: false,
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    };
    
    setMessages([welcomeMessage]);
    
    // 如果有初始问题，自动发送
    if (initialQuestion) {
      setTimeout(() => {
        handleSendMessage(initialQuestion, true);
      }, 500);
    }
  }, []);

  // 自动滚动到底部
  useEffect(() => {
    if (messages.length > 0 && flatListRef.current) {
      setTimeout(() => {
        flatListRef.current.scrollToEnd({ animated: true });
      }, 100);
    }
  }, [messages]);

  // 发送消息
  const handleSendMessage = (text = inputText, isAuto = false) => {
    if (!text.trim()) return;
    
    const newMessage = {
      id: Date.now(),
      text: text.trim(),
      isUser: true,
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    };
    
    setMessages(prevMessages => [...prevMessages, newMessage]);
    if (!isAuto) setInputText('');
    
    // 模拟客服正在输入
    setIsTyping(true);
    
    // 模拟客服回复延迟
    setTimeout(() => {
      // 根据问题获取对应回答
      const replyText = getAnswerForQuestion(text.trim());
      
      const replyMessage = {
        id: Date.now() + 1,
        text: replyText,
        isUser: false,
        time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
      };
      
      setIsTyping(false);
      setMessages(prevMessages => [...prevMessages, replyMessage]);
    }, 1000 + Math.random() * 1000); // 随机延迟1-2秒
  };

  // 渲染消息气泡
  const renderMessage = ({ item }) => {
    return (
      <View style={[styles.messageContainer, item.isUser ? styles.userMessageContainer : styles.agentMessageContainer]}>
        <View style={[styles.messageBubble, item.isUser ? styles.userMessageBubble : styles.agentMessageBubble]}>
          <Text style={[styles.messageText, item.isUser ? styles.userMessageText : styles.agentMessageText]}>
            {item.text}
          </Text>
        </View>
        <Text style={styles.messageTime}>{item.time}</Text>
      </View>
    );
  };

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      style={styles.container}
    >
      <View style={styles.header}>
        <Text style={styles.headerTitle}>在线客服</Text>
        <TouchableOpacity style={styles.closeButton} onPress={onClose}>
          <Ionicons name="close" size={24} color="#666" />
        </TouchableOpacity>
      </View>
      
      <FlatList
        ref={flatListRef}
        data={messages}
        renderItem={renderMessage}
        keyExtractor={item => item.id.toString()}
        contentContainerStyle={styles.messagesList}
        showsVerticalScrollIndicator={false}
      />
      
      {isTyping && (
        <View style={styles.typingContainer}>
          <View style={styles.typingBubble}>
            <Text style={styles.typingText}>客服正在输入</Text>
            <ActivityIndicator size="small" color="#999" style={styles.typingIndicator} />
          </View>
        </View>
      )}
      
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          placeholder="请输入您的问题..."
          value={inputText}
          onChangeText={setInputText}
          multiline
          maxLength={200}
        />
        <TouchableOpacity 
          style={[styles.sendButton, !inputText.trim() && styles.sendButtonDisabled]}
          onPress={() => handleSendMessage()}
          disabled={!inputText.trim()}
        >
          <Ionicons name="send" size={20} color={inputText.trim() ? "#fff" : "#ccc"} />
        </TouchableOpacity>
      </View>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: Platform.OS === 'ios' ? 88 : 56,
    paddingTop: Platform.OS === 'ios' ? 44 : 0,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    position: 'relative',
  },
  headerTitle: {
    fontSize: 17,
    fontWeight: '500',
    color: '#333',
  },
  closeButton: {
    position: 'absolute',
    right: 15,
    bottom: 12,
  },
  messagesList: {
    padding: 10,
    paddingBottom: 20,
  },
  messageContainer: {
    marginVertical: 5,
    maxWidth: '80%',
  },
  userMessageContainer: {
    alignSelf: 'flex-end',
  },
  agentMessageContainer: {
    alignSelf: 'flex-start',
  },
  messageBubble: {
    borderRadius: 18,
    paddingHorizontal: 12,
    paddingVertical: 8,
    maxWidth: '100%',
  },
  userMessageBubble: {
    backgroundColor: '#d0021b',
  },
  agentMessageBubble: {
    backgroundColor: '#fff',
    borderWidth: 1,
    borderColor: '#eee',
  },
  messageText: {
    fontSize: 15,
    lineHeight: 20,
  },
  userMessageText: {
    color: '#fff',
  },
  agentMessageText: {
    color: '#333',
  },
  messageTime: {
    fontSize: 11,
    color: '#999',
    marginTop: 2,
    marginHorizontal: 4,
  },
  typingContainer: {
    paddingHorizontal: 10,
    marginBottom: 5,
  },
  typingBubble: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f0f0f0',
    borderRadius: 18,
    paddingHorizontal: 12,
    paddingVertical: 6,
    alignSelf: 'flex-start',
  },
  typingText: {
    fontSize: 13,
    color: '#666',
    marginRight: 5,
  },
  typingIndicator: {
    marginLeft: 2,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 10,
    paddingVertical: 8,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  input: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    borderRadius: 20,
    paddingHorizontal: 15,
    paddingVertical: 8,
    maxHeight: 100,
    fontSize: 15,
  },
  sendButton: {
    backgroundColor: '#d0021b',
    width: 36,
    height: 36,
    borderRadius: 18,
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: 8,
  },
  sendButtonDisabled: {
    backgroundColor: '#f0f0f0',
  },
});

export default ChatInterface;